import User from '../models/User.js';
import JWTService from '../services/jwtService.js';

// JWT验证中间件
const authMiddleware = async (req, res, next) => {
  try {
    // 从请求头获取token
    const authHeader = req.headers.authorization;
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return res.status(401).json({
        success: false,
        message: '未授权，请提供有效的认证令牌'
      });
    }
    
    // 提取token
    const token = authHeader.split(' ')[1];
    
    // 验证token
    const result = JWTService.verifyToken(token);
    
    if (!result.isValid) {
      return res.status(401).json({
        success: false,
        message: result.error
      });
    }
    
    // 验证令牌类型
    if (result.decoded.type !== 'access') {
      return res.status(401).json({
        success: false,
        message: '无效的访问令牌类型'
      });
    }
    
    // 查找用户
    const user = await User.findByUsername(result.decoded.username);
    if (!user) {
      return res.status(401).json({
        success: false,
        message: '用户不存在'
      });
    }
    
    // 将用户信息和令牌信息添加到请求对象
    req.user = user;
    req.tokenInfo = result.decoded;
    
    next();
  } catch (error) {
    console.error('认证错误:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
};

export default authMiddleware;